function css2Style(contentNode) {
    const len = document.styleSheets.length;
    for (let sheetInd = 0; sheetInd < len; sheetInd++) {
        const cssRules = document.styleSheets[sheetInd].cssRules;
        for (let cssInd = 0; cssInd < cssRules.length; cssInd++) {
            const selectorText = cssRules[cssInd].selectorText;
            const size = cssRules[cssInd]?.styleMap?.size || 0;
            const domList = contentNode.querySelectorAll(selectorText);
            for (let domInd = 0; domInd < domList.length; domInd++) {
                const dom = domList[domInd];
                for (let styleInd = 0; styleInd < size; styleInd++) {
                    const styleName = cssRules[cssInd].style[styleInd];
                    dom.style[styleName] = cssRules[cssInd].style[styleName];
                }
            }
        }
    }
    return contentNode;
}

function saveData(selector, fileName, callBack) {
    const mainEl = document.querySelector(selector);
    if(!mainEl) return '未找到该元素节点';
    const contentNode = mainEl.cloneNode(true);
    const data = wordExport(css2Style(contentNode));
    contentNode.style.maxWidth = window.innerWidth + 'px';
    downLoad(data, fileName, callBack);
}

function removeNotOutElment(contentNode, list = ['.not-out']) {
    for (const listItem of list) {
        const domList = contentNode.querySelectorAll(listItem);
        for (let i = 0; i < domList.length; i++) {
            domList[i].remove();
        }
    }
    return contentNode;
}

function rem2Px(html) {
    const rootSize = document.documentElement.style.fontSize;
    if (!rootSize) return html;
    const sizeNumber = parseInt(rootSize);
    html.replace(/(\d+)rem;/g, function (_, $1) {
        return $1 * sizeNumber + 'px;';
    });
    return html;
}

function wordExport(contentNode) {
    contentNode = removeNotOutElment(contentNode);
    const staticObj = {
        mhtml: {
            top:
                'Mime-Version: 1.0\nContent-Base: ' +
                location.href +
                '\nContent-Type: Multipart/related; boundary="NEXT.ITEM-BOUNDARY";type="text/html"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset="utf-8"\nContent-Location: ' +
                location.href +
                '\n\n<!DOCTYPE html>\n<html>\n_html_</html>',
            head: '<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<style>\n_styles_\n</style>\n</head>\n',
            body: '<body>_body_</body>',
        },
    };
    const options = {
        maxWidth: 1000,
    };
    // Clone selected element before manipulating it
    const markup = contentNode.cloneNode(true);
    // Remove hidden elements from the output

    // Embed all images using Data URLs
    const images = Array();
    const img = markup.getElementsByTagName('img');
    for (let i = 0; i < img.length; i++) {
        let imgW = parseInt(img[i].style.width) || img[i].width;
        let imgH = parseInt(img[i].style.height) || img[i].height;
        // Calculate dimensions of output image
        const w = Math.min(imgW, options.maxWidth);
        const h = imgH * (w / imgW);
        try{
            // Create canvas for converting image to data URL
            const canvas = document.createElement('CANVAS');
            canvas.width = w;
            canvas.height = h;
            // Draw image to canvas
            const context = canvas.getContext('2d');
            context.drawImage(img[i], 0, 0, w, h);
            // Get data URL encoding of image
            const uri = canvas.toDataURL('image/png');
            img[i].setAttribute('src', uri);
            images[i] = {
                type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")),
                encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")),
                location: $(img[i]).attr("src"),
                data: uri.substring(uri.indexOf(",") + 1)
            };
        }catch(err){
            console.warn(err);
        }
        img[i].width = w;
        img[i].height = h;
        img[i].align = img[i].style.float;
    }

    // Prepare bottom of mhtml file with image data
    let mhtmlBottom = '\n';
    for (let i = 0; i < images.length; i++) {
        mhtmlBottom += '--NEXT.ITEM-BOUNDARY\n';
        mhtmlBottom += 'Content-Location: ' + images[i].location + '\n';
        mhtmlBottom += 'Content-Type: ' + images[i].type + '\n';
        mhtmlBottom +=
            'Content-Transfer-Encoding: ' + images[i].encoding + '\n\n';
        mhtmlBottom += images[i].data + '\n\n';
    }
    mhtmlBottom += '--NEXT.ITEM-BOUNDARY--';
    // console.log('markup', markup.innerHTML);
    // Aggregate parts of the file together
    const showHtml = rem2Px(markup.innerHTML);
    const styles = '';
    const fileContent =
        staticObj.mhtml.top.replace(
            '_html_',
            staticObj.mhtml.head.replace('_styles_', styles) +
                staticObj.mhtml.body.replace('_body_', showHtml)
        ) + mhtmlBottom;
    // const fileContent = `<html>${showHtml}</html>`;
    // console.log('%c Line:114 🍕 fileContent', 'color:#f5ce50', fileContent);
    // Create a Blob with the file contents
    const blob = new Blob([fileContent], {
        type: 'application/msword;charset=utf-8',
    });
    return blob;
}
/* 
wps:kswps
docx:msword
*/
function downLoad(data, fileName, callBack) {
    // const blob = new Blob([data], { type: 'application/kswps' });
    const reader = new FileReader();
    reader.readAsDataURL(data);
    reader.onload = (e) => {
        const link = document.createElement('a');
        link.setAttribute('href', e.target.result);
        link.setAttribute('download', `${fileName}.doc`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };
}
// export { css2Style, saveData };
